from django.shortcuts import render, redirect, HttpResponseRedirect
from app01 import models
from app01.utils.pageination import Pagination
from app01.utils.form import PrettyForm, PrettyeditForm
import copy


def pretty_list(request):
    """靓号列表"""
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict['mobile__contains'] = search_data
    queryset = models.PrettyMum.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request, queryset)

    context = {
        'search_data': search_data,
        'queryset': page_object.page_queryset,
        'page_str': page_object.html()
    }
    return render(request, 'pretty_list.html', context)


def pretty_add(request):
    """添加靓号"""
    if request.method == 'GET':
        form = PrettyForm()
        return render(request, 'pretty_add.html', {'form': form})
    form = PrettyForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_add.html', {'form': form})


def pretty_edit(request, nid):
    """修改靓号"""
    row_objects = models.PrettyMum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyeditForm(instance=row_objects)
        return render(request, 'pretty_edit.html', {"form": form})
    form = PrettyeditForm(data=request.POST, instance=row_objects)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request, nid):
    # 获取当前页面的URL
    current_url = request.META.get('HTTP_REFERER', '/pretty/list/')

    models.PrettyMum.objects.filter(id=nid).delete()

    # 重定向到之前的页面
    return HttpResponseRedirect(current_url)
